//
//  User.m
//  FPTest
//
//  Created by zhaohong on 2017/11/21.
//  Copyright © 2017年 zhaohong. All rights reserved.
//

#import "User.h"

static User *segtonInstance = nil;
@implementation User
#define kuname @"uname"// 用户名称


#pragma mark 重写父类方法，防止对象变更
- (id)initWithDataDic:(NSDictionary *)data
{
    //获取用户单例，不生成新的对象
    self = [User shareUserContext];
    [self setAttributes:data];
    return self;
}

- (void)setAttributes:(NSDictionary*)dataDic
{
    [super setAttributes:dataDic];

    //将对象存储到本地
    [self writeToFile];

}

#pragma mark 从本地读取数据或者新生成一个类
+(id)shareUserContext
{
    @synchronized(self){
        if (segtonInstance == nil) {
            //获取设备文件位置
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths firstObject];
            NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"user.archiver"];
            
            segtonInstance = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
            
            if (segtonInstance == nil) {
                segtonInstance = [[[self class]alloc]init];
            }
        }
    }
    return segtonInstance;
}

#pragma mark 将数据写入本地
- (void)writeToFile
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths firstObject];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"user.archiver"];
    BOOL flag =   [NSKeyedArchiver archiveRootObject:segtonInstance toFile:filePath];
    //如果写入失败了则再写入一次，如果还失败，就然并卵吧
    if (!flag) {
        [NSKeyedArchiver archiveRootObject:segtonInstance toFile:filePath];
    }
    
}


#pragma mark 加密
- (void)encodeWithCoder:(NSCoder *)aCoder
{
   
    [aCoder encodeObject:_uname forKey:kuname];// 用户名称
   
}
#pragma mark 解密
- (id)initWithCoder:(NSCoder *)aDecoder
{
    
    if (self) {
        _uname = [aDecoder decodeObjectForKey:kuname];// 用户名称
    }
    
    return self;
}

//修改属性值
- (void)setUname:(NSString *)uname
{
    _uname = uname;
    [self writeToFile];
}

@end
